//
//  DownloadManager.m
//  DownloadDemo
//
//  Created by lanou3g on 16/4/27.
//  Copyright © 2016年 鸥！陈凯. All rights reserved.
//

#import "DownloadManager.h"
#import "MusicDownloadTask.h"
@interface DownloadManagerTask : NSObject
@property (nonatomic,strong) JaneRadioListModel *model;
@property (nonatomic,strong) MusicDownloadTask *downloadTask;
@end
@implementation DownloadManagerTask
- (NSString *)description {
    return self.model.title;
}
@end
@implementation DownloadManager
+ (instancetype)shareManager {
    static DownloadManager *downloadManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        downloadManager = [DownloadManager new];
        downloadManager.array = [NSMutableArray new];
    });
    return downloadManager;
}

- (void)addDownloadTask:(JaneRadioListModel *)model progressBlock:(ProgressBlock)proBlock complete:(CompleteBlock)comBlock {
    //BOOL isContain = NO;
    for (DownloadManagerTask *task in self.array) {
        if ([task.model.title isEqualToString:model.title]) {
            return;
        }
    }
//    包含就不下载
//    if (isContain) {
//        return;
//    }
    MusicDownloadTask *musicTask = [[MusicDownloadTask alloc]init];
    [musicTask downloadUrl:[NSURL URLWithString:model.musicUrl] progressBlock:proBlock complete:comBlock];
//    添加到数组中
    DownloadManagerTask *downloadManagerTask = [DownloadManagerTask new];
    downloadManagerTask.model = model;
    downloadManagerTask.downloadTask = musicTask;
    [self.array addObject:downloadManagerTask];
}
// 当前下载任务个数
- (NSInteger)count {
    return self.array.count;
}
//取值
- (NSString *)getTitleWithIndex:(NSInteger)index {
    DownloadManagerTask *task = self.array[index];
    return task.model.title;
}
- (void)setProgressBlock:(ProgressBlock)proBlock CompleteBlock:(CompleteBlock)comBlock Index:(NSInteger)index {
    DownloadManagerTask *task = self.array[index];
    [task.downloadTask setProgressBlock:proBlock];
    [task.downloadTask setCompleteBlock:^(NSString *path) {
        [self.array removeObjectAtIndex:index];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"DownloadReloadData" object:nil];
    }];
}

@end
